package org.xmx0632.connector.protocol;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.xmx0632.connector.protocol.message.*;
import org.xmx0632.connector.protocol.wrapper.AesWrapper;

import com.alibaba.fastjson.JSON;
import com.codahale.metrics.annotation.Timed;

@Component
public class JsonMessageParser {

	private static final Logger LOG = LoggerFactory.getLogger(JsonMessageParser.class);

	@Timed
	public BaseMessage parse(String msg) {
		// TODO 按照协议中的消息格式解析string为对应的Message对象
		LOG.debug("message:{}", msg);
		if (msg.contains("\"code\":\"0001\"")) {
			return toObject(msg, GatewayRegister0001UpRequest.class);
		}

		if (msg.contains("\"code\":\"0002\"")) {
			return toObject(msg, Heartbeat0002UpRequest.class);
		}
		if (msg.contains("8888")) {
			return new Demo8888UpRequest();
		}
		if (msg.contains("resp_9001")) {
			return new TerminatorsControl1001DownResponse();
		}
		// mock test 下发消息
		if (msg.contains("req_9001")) {
			return new TerminatorsControl1001DownRequest();
		}
		return new InvalidRequest(msg);
	}

	protected <T> T toObject(String string, Class<T> class1) {
		T message = JSON.parseObject(string, class1);
		return message;
	}

	// TODO 把Message对象按照协议格式转换为json字符串
	public String toJsonString(Message msg) {
		LOG.debug("convert msg:{}", msg);
		String string = JSON.toJSONString(msg);
		LOG.debug("jsonString:{}", string);
		return string;
	}

	// 提取AES消息
	public AesWrapper parseWrapperData(String string) {
		LOG.debug("convert string:{}", string);
		AesWrapper msg = JSON.parseObject(string, AesWrapper.class);
		return msg;
	}

}
